const app = getApp();
let util = require('../../utils/util.js');
let tsc = require('../../utils/gprint/tsc.js')
let esc = require('../../utils/gprint/esc.js')
Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
    piaojuText: ''
  },
  // 初始化蓝牙模块
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('初始化蓝牙模块成功', res);
        //开始搜寻附近的蓝牙外围设备
        this.startBluetoothDevicesDiscovery();
      },
      fail: (res) => {
        wx.showToast({title: '初始化蓝牙失败', icon: 'none'});
        console.log('初始化蓝牙模块失败', res);
        //用户蓝牙开关未开启或者手机不支持蓝牙功能
        if (res.errCode === 10001) {
          //监听蓝牙适配器状态变化事件
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('监听蓝牙适配器状态变化事件', res);
            //蓝牙适配器是否可用
            if (res.available) {
              this.startBluetoothDevicesDiscovery();
            }
          })
        }
      }
    })
  },
  //开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      return
    }
    wx.showLoading({title: '设备检索中'});
    this._discoveryStarted = true;
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,//是否允许重复上报同一设备
      success: (res) => {
        console.log('开始搜寻附近的蓝牙外围设备成功', res);
        this.onBluetoothDeviceFound();
      },
      fail: (res) => {
        console.log('开始搜寻附近的蓝牙外围设备失败', res);
        wx.showToast({title: "搜索蓝牙失败", icon: 'none'});
      }
    })
  },
  //寻找到新设备的事件的回调函数
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      console.log('寻找到新设备的事件的回调函数', res);
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices;
        const idx = util.inArray(foundDevices, 'deviceId', device.deviceId);
        const data = {};
        //设备不存在则插入，已存在则更新
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device;
        } else {
          data[`devices[${idx}]`] = device;
        }
        this.setData(data);
      })
    })
  },
  //停止搜索蓝牙设备
  stopBluetoothDevicesDiscovery() {
    if (this._discoveryStarted) {
      wx.stopBluetoothDevicesDiscovery();
      wx.hideLoading();
    }
  },
  //连接低功耗蓝牙设备
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset;
    const deviceId = ds.deviceId;
    const name = ds.name;
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        console.log('连接低功率蓝牙设备成功', res);
        this.setData({
          connected: true,
          name,
          deviceId,
        });
        this.getBLEDeviceServices(deviceId);
      },
      fail: (res) => {
        console.log("蓝牙连接失败:", res);
        wx.showToast({title: '蓝牙连接失败',icon: 'none'});
      }
    });
    this.stopBluetoothDevicesDiscovery();
  },
  //获取蓝牙设备所有服务(service)
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        console.log('获取蓝牙设备所有服务成功', res);
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      },
      fail: (res) => {
        console.log("获取蓝牙服务失败：" + JSON.stringify(res));
        wx.showToast({title: '获取蓝牙服务失败', icon: 'none'});
      }
    })
  },
  //获取蓝牙设备某个服务中所有特征值(characteristic)
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('获取蓝牙设备某个服务中所有特征值成功', res.characteristics);
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i];
          //读取低功耗蓝牙设备的特征值的二进制数据值
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            });
          }
          //向低功耗蓝牙设备特征值中写入二进制数据
          if (item.properties.write) {
            this.setData({
              canWrite: true
            });
            this._deviceId = deviceId;
            this._serviceId = serviceId;
            this._characteristicId = item.uuid;
            this.writeBLECharacteristicValue();
          }
          //启用低功耗蓝牙设备特征值变化时的 notify 功能，订阅特征值
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('获取特征值失败：', res)
      }
    });
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId);
      const data = {};
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data);
    })
  },
  writeBLECharacteristicValue() {
    this.senBleLabel();
    return
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  //断开与低功耗蓝牙设备的连接
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    });
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    });
  },
  //关闭蓝牙模块
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter({
      success: res => {
        this._discoveryStarted = false;
        wx.showToast({title: '蓝牙模块关闭'});
      },
      fail: res => {
        console.log('关闭蓝牙模块失败', res);
      }
    });
  },
  //获取本机蓝牙适配器状态
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  //标签模式
  senBleLabel() {
    let deviceId = this._deviceId;
    let serviceId = this._serviceId;
    let characteristicId = this._characteristicId;
    var command = tsc.jpPrinter.createNew();
    // console.log(command)
    command.setSize(40, 30);
    command.setGap(2);
    command.setCls();
    command.setText(50, 10, "TSS24.BF2", 1, 1, "打印测试");
    command.setQR(50, 50, "L", 5, "A", "977767937@qq.com");
    command.setPagePrint();
    this.senBlData(deviceId, serviceId, characteristicId,command.getData());
  },
  //票据模式
  senBleLabel2() {
    let deviceId = this._deviceId;
    let serviceId = this._serviceId;
    let characteristicId = this._characteristicId;
    var command = esc.jpPrinter.createNew();
    command.init();
    console.log(this.piaojuText);
    command.setText("采购单\n");
    command.setText("大白菜     5千克\n");
    command.setText("土豆       5千克\n");
    command.setText("牛肉       5千克\n");
    command.setText("花菜       5千克\n");
    command.setText("西红柿     5千克\n");
    command.setText("青辣椒     5千克\n");
    command.setPrintAndFeedRow(2);
    this.senBlData(deviceId, serviceId, characteristicId,command.getData());
  },
  senBlData(deviceId, serviceId, characteristicId, uint8Array) {
    console.log('************deviceId = [' + deviceId + ']  serviceId = [' + serviceId + '] characteristics=[' +characteristicId+ "]");
    var uint8Buf = Array.from(uint8Array);
    function split_array(datas,size){
      var result = {};
      var j = 0;
      for (var i = 0; i < datas.length; i += size) {
        result[j] = datas.slice(i, i + size);
        j++;
      }
      console.log(result);
      return result;
    }
    var sendloop = split_array(uint8Buf, 20);
    // console.log(sendloop.length)
    function realWriteData(sendloop, i) {
      var data = sendloop[i];
      if(typeof(data) == "undefined"){
        return
      }
      console.log("第【" + i + "】次写数据"+data);
      var buffer = new ArrayBuffer(data.length);
      var dataView = new DataView(buffer);
      for (var j = 0; j < data.length; j++) {
        dataView.setUint8(j, data[j]);
      }
      wx.writeBLECharacteristicValue({
        deviceId,
        serviceId,
        characteristicId,
        value: buffer,
        success(res) {
          realWriteData(sendloop, i + 1);
        }
      })
    }
    var i = 0;
    realWriteData(sendloop, i);
  }
})